'use client';

import { useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import styles from "./change-password.module.css";

const ChangePasswordPage = () => {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  
  // 表单状态
  const [formData, setFormData] = useState({
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
  });
  
  // 错误提示状态
  const [errors, setErrors] = useState({
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
  });

  // 未登录跳转
  if (status === "unauthenticated") {
    router.push("/dashboard/login");
    return null;
  }

  // 加载中状态
  if (status === "loading") {
    return <div className={styles.loading}>加载中...</div>;
  }

  // 输入变化处理
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误提示
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: "" }));
    }
  };

  // 密码强度提示
  const getPasswordStrength = () => {
    const { newPassword } = formData;
    if (newPassword.length < 8) return "至少8个字符";
    if (!/[A-Z]/.test(newPassword)) return "需要包含大写字母";
    if (!/[a-z]/.test(newPassword)) return "需要包含小写字母";
    if (!/\d/.test(newPassword)) return "需要包含数字";
    if (!/[@$!%*?&]/.test(newPassword)) return "需要包含特殊字符（@$!%*?&）";
    return "密码强度：强";
  };

  // 表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErrors({});

    try {
      // 前端二次校验
      const newErrors = {};
      if (!formData.oldPassword) newErrors.oldPassword = "请输入旧密码";
      if (!formData.newPassword) newErrors.newPassword = "请输入新密码";
      if (!formData.confirmPassword) newErrors.confirmPassword = "请确认新密码";
      
      if (formData.newPassword !== formData.confirmPassword) {
        newErrors.confirmPassword = "两次输入的密码不一致";
      }
      
      if (!/^.{8,}$/.test(formData.newPassword)) {
        newErrors.newPassword = "新密码至少8个字符";
      }

      if (Object.keys(newErrors).length > 0) {
        setErrors(newErrors);
        setLoading(false);
        return;
      }

      // 调用接口
      const res = await fetch("/api/auth/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData)
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "修改密码失败");
      }

      // 成功处理：提示并退出登录
      toast.success(data.message);
      signOut({ callbackUrl: "/dashboard/login" });

    } catch (err) {
      toast.error(err.message);
      // 特殊错误字段定位（如旧密码错误）
      if (err.message.includes("旧密码")) {
        setErrors({ oldPassword: err.message });
      } else if (err.message.includes("新密码")) {
        setErrors({ newPassword: err.message });
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>修改密码</h1>
      <p className={styles.subtitle}>请输入旧密码和新密码完成修改</p>

      <form onSubmit={handleSubmit} className={styles.form}>
        {/* 旧密码 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>旧密码</label>
          <input
            type="password"
            name="oldPassword"
            value={formData.oldPassword}
            onChange={handleChange}
            className={`${styles.input} ${errors.oldPassword ? styles.errorInput : ""}`}
            placeholder="请输入当前密码"
          />
          {errors.oldPassword && (
            <span className={styles.errorText}>{errors.oldPassword}</span>
          )}
        </div>

        {/* 新密码 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>
            新密码
            <span className={styles.helperText}>（至少8位，包含大小写字母、数字和特殊字符）</span>
          </label>
          <input
            type="password"
            name="newPassword"
            value={formData.newPassword}
            onChange={handleChange}
            className={`${styles.input} ${errors.newPassword ? styles.errorInput : ""}`}
            placeholder="请设置新密码"
          />
          {/* 密码强度提示 */}
          <span className={styles.strengthText}>
            {getPasswordStrength()}
          </span>
          {errors.newPassword && (
            <span className={styles.errorText}>{errors.newPassword}</span>
          )}
        </div>

        {/* 确认新密码 */}
        <div className={styles.formGroup}>
          <label className={styles.label}>确认新密码</label>
          <input
            type="password"
            name="confirmPassword"
            value={formData.confirmPassword}
            onChange={handleChange}
            className={`${styles.input} ${errors.confirmPassword ? styles.errorInput : ""}`}
            placeholder="请再次输入新密码"
          />
          {errors.confirmPassword && (
            <span className={styles.errorText}>{errors.confirmPassword}</span>
          )}
        </div>

        <button
          type="submit"
          disabled={loading}
          className={styles.button}
        >
          {loading ? "修改中..." : "确认修改"}
        </button>

        <button
          type="button"
          onClick={() => router.back()}
          className={styles.cancelButton}
        >
          取消
        </button>
      </form>
    </div>
  );
};

export default ChangePasswordPage;